<?php
namespace control;
// 文档目录
class documentManagementClass extends adIndexClass
{
    private const page  = 'documentManagement'; # 权限
    private const table = 'document'; # 数据表
    private const title = '文章';

    /*文章入口页*/
    public function home()
    {
        $option['click'] = 'replaceContent(this, \'documentManagement\')';
        $all = documentCatalogClass::getCatalogAll($option);

        //返回
        $rightHtml = $this->homeRight();
        $html =  componentClass::leftNav([
            'title'=>'搜索文章',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        //返回
        return $this->homeFun($html);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson():string
    {
        $option['click'] = 'replaceContent(this, \'documentManagement\')';
        $json['html'] = documentCatalogClass::getCatalogAll($option);
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "文章名称" => text(array("name" => "name")),
                    "文章描述"   => text(array("name" => "text")).hidden(['name'=>'objId', 'value' => $this->post('objId')]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight()
    {
        // 搜索
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit") && $this->post('objId')) {
            $root = $this->root.'control/adIndex.html?cla='.$this->get('cla').'&fun=editPage&id='.self::getId().'&dcid='.$this->post('objId');
            $button .= "<span class='spanButton' onclick=\"newIframe('新建文章','".$root."')\">新建</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        $button .= componentClass::tipComponent("<p>1、规章制度内容需建立文档目录'规章制度'</p><p>2、小程序端内容需建立文档目录如：'oa小程序端','crm小程序端'等</p><p>3、小程序更新日志需设置文档标题为'更新日志'</p><p>4、小程序关于内容需设置文档标题为'公司介绍'</p>",allowHTML: true);
        return $this->search($html, layout: 'pop', toolButton: $button);
    }
    /**
     * 异步加载
     *
     */
    public function homeRightJson()
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }
    public function homeRightJsonSearch()
    {
        return $this->homeSearch();
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => '分类',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "文章编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'title'  => [
                        'name'  => "标题",
                        'width' => 200,
                    ],
                    'publicStid'         => [
                        'name'  => '发布人',
                        'width' => 100,
                    ],
                    'publicTime'          => [
                        'name'  => '发布时间',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'selector'          => [
                        'name'  => '查看范围',
                        'width' => 200,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*文章列表*/
    public function homeSearch()
    {
        //like查询数组
        $like = [
            "name" => $this->post('name'),   //文章名称
            "text" => $this->post('text'),   //文章名称
        ];
        //全等查询数组
        $equal = [
            'dcid' => $this->post('objId'),
        ];
        //分类查询
        $and = "";
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like,"=" => $equal)).$and;
        $page = $this->page(array("table" => self::table,"where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate  = array(
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => "文章详情", "click" => "newIframe('文章详情','".root."control/adIndex.html?cla=documentManagement&fun=detail&id=".$array['id']."')"],
                'preview'=> ["title" => "文章详情", "click" => "newIframe('文章详情','".root."control/adIndex.html?cla=documentCenterClass&fun=detail&id=".$array['id']."')"]
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "type":
                        $row[] = documentCatalogClass::getTypeName($array['dcid']);
                        break;
                    case "publicStid":
                        $row[] = self::findStaff($array['publicStid']);
                        break;
                    case "selector":
                        $row[] = componentClass::showSelector($array['selector']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'].$button."<form name='listForm'>".$li."</form>".$page['button'].clear;
        return json_encode($json, 320);
    }

    public static function getCatalogName($id)
    {
        $temp = '';
        if ($id) {
            $info = query('document_catalog', " id = '$id' ");
            if ($info['pid'] == '0') {
                $temp .= $info['name'];
            } else {
                $temp .= self::getCatalogName($info['pid']).' > '. $info['name'];
            }
        }
        return $temp;
    }


    public function editPage()
    {
        $info = query(self::table, " id = '".$this->get('id')."' ");
        $html  =  '';
        if (empty($this->get('dcid')) && empty($info)) {
            $data['html'] = '请选择分类';
        } else {
            $dcid = $info['dcid'] ?: $this->get('dcid');
            $content = self::htmlDecode($info['content']);
            $button[] = [
                'style' => 'li-btn-blue-bg',
                "name"  => "保存",
                "type"  => "点击事件",
                "title" => "保存",
                'fun'   => "setContent();subForm('" . self::page . "EditPageForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editPageEdit')",
            ];
            //表单
            $data['html'] = $this->layerEdit([
            "table" => [
                [
                    $this->tableShowButton($button),
                ],
                [
                    '分类' => self::getCatalogName($dcid).hidden(['name' => "dcid", 'class'=> 'text', 'value' => $dcid]),
                ],
                [
                    must.'标题' => text(['name' => "title", 'class'=> 'text', 'value' => $info['title']])
                                .hidden(['name' => "orderNo", 'value' => $info['orderNo'] ?? codeTemplateClass::generateCode(self::page,[
                                'table'   => 'document',
                                'prefix'  => 'AR'.date('Ymd'),
                                'default' => '001'
                            ],[])]),
                ],
                [
                    must.'查看范围' => componentClass::staffSelector($info['selector']),
                ],
                [
                    '摘要' => textarea(['name' => "summary", 'class'=> 'text', 'value' => $info['summary']]),
                ],
                [
                ],
                [
                    '文章详情' => '<div id="content" style="width:70%"></div>'.hidden(['name'=> 'id', 'value'=> $info['id'] ?:  $this->get('id') ]).hidden(['name'=>'content', 'id'=> $this->get('id').'-body']).hidden(['name'=>'pics', 'id'=> 'pics' ]),
                ],[
                    "附件" => fileUploadClass::addFileComponent($info['id'], '文档管理', self::page, self::page . 'EditPageForm')
                ]
            ],
            'button'=> ' ',
        ]);
            $html =<<<EOT
        <script type="text/javascript"  src="{$this->root}static/javascript/wangEditor.min.js	"></script>
        <script type="text/javascript">
            const E = window.wangEditor
            const editor = new E("#content")
            editor.config.menus = [
                'head',
                'bold',
                'fontSize',
                'fontName',
                'italic',
                'underline',
                'strikeThrough',
                'indent',
                'lineHeight',
                'foreColor',
                'backColor',
                'link',
                'list',
                'todo',
                'justify',
                'quote',
                'emoticon',
                'image',
                'video',
                'table',
                'code',
                'splitLine',
                'undo',
                'redo',
            ]
            editor.config.uploadImgMaxLength = 5
            editor.config.uploadImgMaxSize = 2 * 1024 * 1024
            editor.config.zIndex = 1
            editor.config.showLinkImg = false
            editor.config.uploadFileName = 'file'
            editor.config.uploadImgServer = root + 'control/adIndex.html?cla=documentManagement&fun=uploadImg'
            editor.config.uploadImgHooks = {
                success: function(xhr, editor, resData) {
                    let pic = $('#pics').val()
                    $('#pics').val(pic + resData['fid'])
                },
                error: function(xhr, editor, resData) {
                    msg('上传图片失败', 'error')
                    return
                },
                timeout: function(xhr) {
                    msg('上传图片超时', 'error')
                    return
                }
            }
            editor.create()
            editor.txt.append(`{$content}`)
            function setContent(){
                let body = editor.txt.html()
                $('#{$this->get('id')}-body').val(body)
            }
        </script>
EOT;
        }
        //返回
        return $this->tab($data).$html;
    }

    /**
     * 上传图片
     *
     * @return string
     */
    public function uploadImg():string
    {
        $data = [];
        $fid = '';
        if (isset($_FILES)) {
            foreach ($_FILES as $file) {
                $result = $this->saveFile($file, self::page, ['jpg', 'jpeg', 'png', 'gif', 'bmp']);
                if ($result['code']) {
                    $data[] = [
                        'url' => root . $result['src'],
                        'alt' => $result['fileName'],
                    ];
                    $id = self::getId();
                    static::insert([
                        'table' => 'file',
                        'field' => [
                            'id'     => $id,
                            'stid'   => $this->control['stid'],
                            'target' => '文章图片',
                            'name'   => $result['fileName'],
                            'format' => $result['suffix'],
                            'size'   => $result['size'],
                            'src'    => $result['src']
                        ]
                    ]);
                    $fid .= $id.';';
                }
            }
        }
        $resp = [
            'errno' => 0,
            'data'  => $data,
            'fid'   => $fid
        ];
        return json_encode($resp, 320);
    }

    /*成本表基本资料新增或修改-异步处理*/
    public function editPageEdit()
    {
        $id = $this->post('id') ?: self::getId();
        //附件
        $fileIdArr = $this->post('fileId');
        $pics      = $this->post('pics');
        $field = [
            'dcid'       => $this->post('dcid'),
            'title'      => $this->post('title'),
            'summary'    => $this->post('summary'),
//            'viewScope'  => $this->post('viewScope'),
            // 'publicStid' => $this->post('publicStid'),
            // 'publicTime' => $this->post('publicTime'),
            // 'state'      => $this->post('state'),
            'selector'       => $this->post('staff')[0]??'',//员工选择器
            'content'    => $this->post('content'),
        ];
        $staff = componentClass::returnStaffId($field['selector']);
        $field['member'] = implode(',',$staff);
        $annotation = [
            'dcid'       => '分类ID',
            'title'      => '标题',
            'summary'    => '摘要',
            'selector'  => '查看范围',
            // 'publicStid' => '发布人',
            // 'publicTime' => '发布时间',
            // 'state'      => '状态',
            'content'    => '文章详情',
        ];
        $rules = [
            'dcid'       => 'required',
            'title'      => 'required',
            // 'summary'    => 'required',
            'selector'  => 'required',
            // 'publicStid' => 'required',
            // 'publicTime' => 'required',
            // 'state'      => 'required',
            'content'    => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑".self::title."的权限";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            // if (sqlNum(self::table, " (name = '{$field['name']}' AND tel = '{$field['tel']}') AND id <> '$id'   ") > 0) {
            //     $json['warn'] = "联系人「{$field['name']}」手机号 「{$field['tel']}」重复";
            //     goto resp;
            // }
//            $field['viewScope'] = json_encode($this->post('viewScope'), true);
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page,[
                    'table'   => 'document',
                    'prefix'  => 'AR'.date('Ymd'),
                    'default' => '001'
                ],$field);
                $field    = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $orderNo,
                    'state'   => '草稿',
                    'stid'    => $this->control['stid'],
                    'time'    => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                if (is_array($fileIdArr)) {
                    $fileArray = array_merge($fileIdArr, self::filterArray(explode(';', $pics)));
                    static::update(['table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileArray) . "')"]);
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了".self::title." id：【" . $id.'】'.($field['title'] ? "，标题【{$field['title']}】" : '');
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href'] = root . "control/adIndex.html?cla=".$this->get('cla')."&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    public function detail()
    {
        $info = query(self::table, " id = '".$this->get('id')."' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];
            if ($this->power(self::page, "del")) {
                $button[] = [
                    "name"  => "删除",
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act"=>'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "edit")) {
                if ($info['state'] == '草稿') {
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑文档",
                        "url"   => $this->root.'control/adIndex.html?cla='.$this->get('cla').'&fun=editPage&id='.$info['id'],
                    ];
                }
                $button[] = [
                    "name" => ($info['state']) == "草稿" ? '发布' : '撤销',
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'changeState', "id" => $info['id'] , 'state'=> $info['state']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                "基本信息"   => [
                    [
                        "文章编号" => $info['orderNo'],
                        "创建人"  => self::findStaff($info['stid']),
                        "创建时间" => self::null($info['time']),
                        "分类" => self::getCatalogName($info['dcid']),
                    ],
                    [
                        "标题" => $info['title'],
                        "发布人"  => self::findStaff($info['publicStid']),
                        "发布时间" => self::null($info['publicTime']),
                        "状态"   => $info['state'],
                    ],
                    [
                        "查看范围" => componentClass::showSelector($info['selector']),
                    ],
                    [
                        "摘要" => pre($info['summary']),
                    ],
                ],
                "文章详情" => [
                    [
                        0 => self::htmlDecode($info['content'], true),
                    ],
                ],
                '附件'=> [
                    [
                        fileUploadClass::showFile($info['id'], '文档管理')
                    ]
                ]
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd =$word= false; // 需要密码
        $form = $power ='';
        switch ($act) {
            case 'changeState':
                $act = 'edit';
                $msg = self::title.'修改状态';
                $title = '是否确认发布？';
                $function = 'changeState';
                $form = self::page.'OperateForm, listForm';
                if ($this->post('state') == '已发布') {
                    $title = '是否确认撤销发布？';
                }
                $word = true;
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除'.self::title;
                $title = self::page.'Delete';
                $function = 'isDelete';
                $form = self::page.'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'=>$word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 修改状态
     *
     */
    public function changeState()
    {
        $array = $this->post('listId') ?? $this->post('id');
        $act = 'edit';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = "你没有此权限的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 修改field
            $fieldKey = 'state';
            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    $fieldVlaue = ($info['state'] == '已发布') ? '草稿' : '已发布';
//                    $viewScope = $this->post('viewScope') ? json_encode($this->post('viewScope'), true) : $info['viewScope'];
                    // 修改状态
                    static::update([
                        "table" => self::table,
                        'field' => [
                            $fieldKey    => $fieldVlaue,
//                            'viewScope'  => $viewScope,
                            'publicStid' => self::$stid,
                            'publicTime' => $this->time
                        ],
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= "管理员{$this->control['name']}修改了一条".self::title."：ID【{$id}】".($info['title'] ? "，标题【{$info['title']}】" : '').'<br>';
                    $x++;
                }
            }
            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "修改了{$x}条".self::title;
            $json['warn']     = 2;
//            $json['href'] = root."control/adIndex.html?cla=".$this->get('cla')."&fun=home";
        }
        resp:
        return json_encode($json, 320);
    }


    // 确认删除信息
    public function isDelete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除".self::title."的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field
            $fieldKey = 'state';
            $fieldVlaue = '已发布';

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if ($info[$fieldKey] == $fieldVlaue) {
                        $text .= self::title."【{$info['id']}】为{$fieldVlaue}状态，无法删除<br>";
                        continue;
                    }
                    // 删除相关 附件
                    $result = (array) $this->sqlFind("SELECT id, src FROM `file` WHERE targetId = '{$info['id']}' ");
                    foreach ($result as $key => $file) {
                        delete([
                            'table' => 'file',
                            'where' => " id = '{$file['id']}'",
                        ]);
                        fileDelete($file['src']);
                    }
                    // 删除子表
                    // delete([
                    //     "table" => self::table.'Mx',
                    //     "where" => " orderId = '$id' "
                    // ]);
                    // 删除表
                    delete([
                        "table" => self::table,
                        "where" => $where
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条".self::title."：ID【{$id}】".($info['title'] ? "，标题【{$info['title']}】" : '').'<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条".self::title;
            $json['warn']     = 2;
            $json['href'] = root."control/adIndex.html?cla=".$this->get('cla')."&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }
}
